package com.soonfor.evaluate.tools;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class CommonUtils {

    /**
     * 大陆号码或香港号码均可
     */
    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^(1[0-9])\\d{9}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数，5|6|8|9开头+7位任意数
     */
    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public static void callPhone(String number, Context context) {
        if (!TextUtils.isEmpty(number)) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                ComToast.showToast(context, "请打开电话权限");
                return;
            }
            context.startActivity(intent);
        }
    }

    /**
     * 根据录音文件网络路径 获取时长
     *
     * @param mUri
     * @return
     */
    public static long getRingDuring(String mUri) {
        String duration = null;
        mUri = UserInfo.DOWNLOAD_FILE + "?filepath=" + mUri;
        android.media.MediaMetadataRetriever mmr = new android.media.MediaMetadataRetriever();

        try {
            if (mUri != null) {
                HashMap<String, String> headers = null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                    headers.put("User-Agent",
                            "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            }

            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            mmr.release();
        }
        if (duration == null || duration.equals("")) {
            return 0;
        }
        return Long.parseLong(duration);
    }

    /**
     * 获取百分比
     */
    public static String formatPercentage(String string) {
        if (string == null || string.equals("null") || string.equals("")) {
            return "0.0";
        } else {
            float fs = 0;
            try {
                fs = Float.parseFloat(string);
            } catch (Exception e) {
            }
            if (fs == 0) {
                return "0.0";
            } else {
                if (fs < 1) {
                    fs = fs * 100;
                }
                java.text.DecimalFormat df = new java.text.DecimalFormat("#.0");
                try {
                    return df.format(fs);
                } catch (Exception e) {
                    return "0.0";
                }
            }
        }
    }

    /**
     * 保留一位小数
     *
     * @param string
     * @return
     */
    public static String formatAdecimal(String string) {
        if (string == null || string.equals("null") || string.equals("")) {
            return "0.0";
        } else {
            double sd = 0;
            try {
                sd = Double.parseDouble(string);
            } catch (Exception e) {
            }
            if (sd == 0) {
                return "0.0";
            } else {
                java.text.DecimalFormat df = new java.text.DecimalFormat("#.0");
                try {
                    String result = df.format(sd);
                    if (result.startsWith(".")) {
                        result = "0" + result;
                    }
                    return result;
                } catch (Exception e) {
                    return string;
                }
            }
        }
    }

    // 获取精确的小数（去多余的0）
    public static String getExactStrNum(String str) {
        if (str == null || str.equals("")) {
            return "";
        } else {
            String bigD = (new BigDecimal(str).stripTrailingZeros())
                    .toPlainString();
            // 如果是0.00000则不能去多余的0
            if (bigD.contains(".")) {
                String tou = bigD.substring(0, bigD.indexOf("."));
                if (tou.equals("0") && bigD.charAt(bigD.length() - 1) == '0') {
                    bigD = "0";
                }
            }
            return bigD;
        }
    }

    public static String formatStr(String str) {
        if (str == null || str.equals("null")) {
            return "";
        } else {
            return str;
        }
    }

    public static String formatNum(String str) {
        if (str == null || str.trim().equals("null") || str.trim().equals("")) {
            return "0";
        } else {
            return str.trim();
        }
    }

    public static void setSex(TextView textView, String name, String sex) {
        if (textView != null) {
            if (!sex.equals("")) textView.setText(name + "(" + sex + ")");
            else textView.setText(name);
        }
    }

    public static String formatStrTime(String str) {
        if (str == null || str.equals("null")) {
            return "";
        } else {
//            String thisYear = DateTool.getTimeTimestamp(System.currentTimeMillis(), "yyyy");
//            if(str.substring(0, 4).equals(thisYear)){
//                str = str.substring(5, str.length());
//            }
            if (str.contains(":") && (str.lastIndexOf(":") - str.indexOf(":") > 0)) {
                return str.substring(0, str.lastIndexOf(":"));
            }
            return str;
        }
    }

    /**
     * 隐藏软键盘(可用于Activity，Fragment)
     */
    public static void hideSoftKeyboard(Context context, List<View> viewList) {
        if (viewList == null) return;
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        for (View v : viewList) {
            inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 隐藏软键盘(可用于Activity，Fragment)
     */
    public static void hideSoftKeyboard(Context context, View view) {
        if (view == null) return;
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    // 判断一个字符是否是中文
    public static boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null)
            return false;
        for (char c : str.toCharArray()) {
            if (isChinese(c))
                return true;// 有一个中文字符就返回
        }
        return false;
    }

    public static String IMEI = "";

    /**
     * 获取IMEI
     **/
    public static String getIMEI(Context context) {
        if (context != null) {
            String imei = "";
            try {
                imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
            } catch (SecurityException e) {
                e.getMessage();
            } catch (Exception ee) {
                ee.getMessage();
            }
            IMEI = imei;
        }
        return IMEI;
    }

    //生成一个request 范围为0~65535
    public static int getRequestCode(String _id) {
        String id = _id.trim();
        int len = id.length();
        if(len > 5) {
            return Integer.parseInt(id.substring(len-5));
        }else {
            long num = Long.parseLong(id);
            if (num >= 65535) {
                return (int) (num - 65535);
            }else return Integer.parseInt(id);
        }
    }
}
